package com.twb.core.exception;

import java.util.List;

import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.twb.core.base.Result;
import com.twb.core.constants.BaseEnums;
import com.twb.core.util.Results;
/**
 * @Title GlobalExceptionConfig
 * @Description 全局异常处理
 * @author DSY
 * @date 2018-10-18 14:16
 */
@RestControllerAdvice
public class GlobalExceptionConfig {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionConfig.class);

    /**
     * 处理 ServiceException 异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result<String> handleServiceException(ServiceException e){
        Result<String> result = Results.failure(e.getCode(), e.getMessage());
        result.setStatus(1000);
        logger.error("ServiceException[code: {}, message: {}]", e.getCode(), e.getMessage());
        return result;
    }

    /**
     * 处理 AuthorityException 异常
     */
    @ExceptionHandler(AuthorityException.class)
    public Result<String> handleAuthorityException(AuthorityException e){
        Result<String> result = Results.failure(BaseEnums.FORBIDDEN.code(), BaseEnums.FORBIDDEN.desc());
        result.setStatus(HttpStatus.FORBIDDEN.value());
        logger.error("AuthorityException", e.getMessage());
        return result;
    }
    /**
     * @Title  handleTokenException
     * @Class: GlobalExceptionConfig.java
     * @Description 令牌异常处理
     * @param e
     * @return
     * @author DSY
     * @date 2018年11月3日 下午7:12:11
     */
    @ExceptionHandler(TokenException.class)
    public Result<String> handleTokenException(TokenException e){
    	Result<String> result = Results.failure(BaseEnums.UNAUTHORIZED.code(), BaseEnums.UNAUTHORIZED.desc());
    	result.setStatus(HttpStatus.UNAUTHORIZED.value());
    	logger.error("TokenException",e.getMessage());
    	return result;
    }

    /**
     * 处理 NoHandlerFoundException 异常. <br/>
     * 需配置 [spring.mvc.throw-exception-if-no-handler-found=true]
     * 需配置 [spring.resources.add-mappings=false]
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<String> handleNotFoundException(NoHandlerFoundException e){
        Result<String> result = Results.failure(BaseEnums.NOT_FOUND.code(), BaseEnums.NOT_FOUND.desc());
        result.setStatus(HttpStatus.NOT_FOUND.value());
        logger.error(e.getMessage());
        return result;
    }

    /**
     * 处理 BaseException 异常
     */
    @ExceptionHandler(BaseException.class)
    public Result<String> handleBaseException(BaseException e){
        Result<String> result = Results.failure(e.getCode(), e.getMessage());
        result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        logger.error("BaseException[code: {}, message: {}]", e.getCode(), e.getMessage(), e);
        return result;
    }

    /**
     * @Title handleHttpRequestMethodNotSupportedException
     * @Description 处理HttpRequestMethodNotSupportedException异常
     * @param e
     * @return com.tw.core.base.Result
     * @author DSY
     * @date 2018-10-17
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        Result<String> result = Results.failure(BaseEnums.METHOD_NOT_ALLOWED.code(), BaseEnums.METHOD_NOT_ALLOWED.desc());
        result.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        logger.error("HttpRequestMethodNotSupportedException[code: {}, message: {}]", BaseEnums.FAILURE.code(), e.getMessage(), e);
        return result;
    }
    /**
     * 处理 Exception 异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e){
        Result<String> result = Results.failure(BaseEnums.ERROR.code(), BaseEnums.ERROR.desc()+":"+e.getMessage());
        result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        logger.error(BaseEnums.ERROR.desc(), e);
        return result;
    }
    /**
     * @Title  handleRedisConnectionFailureException
     * @Class: GlobalExceptionConfig.java
     * @Description redis服务器连接异常
     * @param e
     * @return
     * @author DSY
     * @date 2019年12月28日 下午8:39:09
     */
    @ExceptionHandler(RedisConnectionFailureException.class)
    public Result<String> handleRedisConnectionFailureException(RedisConnectionFailureException e){
    	Result<String> result = Results.failure(BaseEnums.ERROR.code(), BaseEnums.ERROR.desc()+":redis服务器连接异常");
    	result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    	logger.error(BaseEnums.ERROR.desc(), e);
    	return result;
    }
    /**
     * @Title  handleVersionUpdateException
     * @Description 乐观锁异常处理
     * @param e
     * @return
     * @author DSY
     * @date 2018年11月1日 下午6:35:17
     */
    @ExceptionHandler(VersionUpdateException.class)
    public Result<String> handleVersionUpdateException(VersionUpdateException e){
    	Result<String> result = Results.failure(BaseEnums.VERSION_NOT_MATCH.code(), BaseEnums.VERSION_NOT_MATCH.desc());
        result.setStatus(HttpStatus.HTTP_VERSION_NOT_SUPPORTED.value());
        logger.error(e.getMessage(), e);
        return result;
    }
    
    /**
     * @Title  handleBindException
     * @Description 参数对象验证异常处理
     * @param e
     * @return
     * @author DSY
     * @date 2018年11月7日 下午4:11:48
     */
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e){
    	List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
    	StringBuffer msg = new StringBuffer();
    	for (FieldError error : fieldErrors) {
    		String defaultMessage = error.getDefaultMessage();
    		String field = error.getField();
    		String errorStr = field+": "+defaultMessage+",";
    		msg.append(errorStr);
		}
    	Result<String> result = Results.failure(BaseEnums.PARAMETER_ERROR.code(),msg.substring(0,msg.length()-1).toString());
    	result.setStatus(HttpStatus.BAD_REQUEST.value());
    	logger.error(e.getMessage(), e);
    	return result;
    }
    /**
     * @Title  handleConstraintViolationException
     * @Description 方法参数校验异常
     * @param e
     * @return
     * @author DSY
     * @date 2018年11月7日 下午5:05:28
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handleConstraintViolationException(ConstraintViolationException e){
    	Result<String> result = Results.failure(BaseEnums.PARAMETER_ERROR.code(),e.getMessage());
    	result.setStatus(HttpStatus.BAD_REQUEST.value());
    	logger.error(e.getMessage(), e);
    	return result;
    }
    
    /**
     * @Title  handleSystemException
     * @Description 系统级别异常拦截处理
     * @param e
     * @return
     * @author DSY
     * @date 2018年11月7日 下午5:05:28
     */
    @ExceptionHandler(SystemException.class)
    public Result<String> handleSystemException(SystemException e){
    	Result<String> result = Results.failure(BaseEnums.ERROR.code(), BaseEnums.ERROR.desc()+":"+e.getMessage());
        result.setStatus(HttpStatus.EXPECTATION_FAILED.value());
        logger.error(BaseEnums.ERROR.desc(), e);
    	return result;
    }
    
    /**
     * @Title handleMethodArgumentNotValidException
     * @Description 方法参数校验异常
     * @param e
     * @return
     * @author DSY
     * @date 2019年12月18日 上午11:58:18
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
    	StringBuffer errorMessage = new StringBuffer("传入参数异常：");
    	List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
    	for (FieldError fieldError : fieldErrors) {
    		String field = fieldError.getField();
    		String defaultMessage = fieldError.getDefaultMessage();
    		errorMessage.append(field+":"+defaultMessage+";");
		}
    	Result<String> result = Results.failure(BaseEnums.PARAMETER_ERROR.code(),errorMessage.toString());
    	result.setStatus(HttpStatus.BAD_REQUEST.value());
    	logger.error(errorMessage.toString());
    	return result;
    }
}